//
/*******************************************************************************
 
 File name:     MessageImageContent.swift
 Author:        danzel_duan
 Gitee.com:     https://gitee.com/danzel-duan/YBIMKit
 E-mail:        danzel_duan@163.com
 
 Description: Copyright © danzel_duan. All rights reserved.
 
 Created by danzel on 2018/12/31.
 
 ********************************************************************************/

import UIKit

public class MessageImageContent: NSObject, MessageContentable {
    public static var viewType: MessageContentViewable.Type {
        return MessageImageContentView.self
    }
    public weak var delegate: MessageDelegate?
    public var layoutMargins: UIEdgeInsets = UIEdgeInsets.zero
    public var image: UIImage?
    public var thumbnailSize: CGSize?
    public var imageSize: CGSize?
    
    public init(image: UIImage) {
        self.image = image
    }
    
    public override init() {}
    
    public func sizeThatFits() -> CGSize {
        if image == nil || image?.size == CGSize.zero || imageSize == CGSize.zero {
            image = createImage(color: UIColor.hexadecimalColor(hex: 0xCDD0D1), size: CGSize.init(width: 160, height: 160))
        }
        let size = imageSize ?? (image?.size)!
        let scale = min(min(160, size.width) / size.width, min(160, size.height) / size.height)
        let w = size.width * scale
        let h = size.height * scale
        return .init(width: w, height: h)
    }
}

public func createImage(color: UIColor, size: CGSize) -> UIImage? {
    var rect = CGRect(origin: CGPoint.zero, size: size)
    UIGraphicsBeginImageContext(size)
    defer {
        UIGraphicsEndImageContext()
    }
    let context = UIGraphicsGetCurrentContext()
    context?.setFillColor(color.cgColor)
    context?.fill(rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    return image
}

public extension UIColor {
    /// 16进制转 color
    ///
    /// - Parameters:
    ///   - hex: 16进制数值
    ///   - alpha: alpha
    /// - Returns: color
    public class func hexadecimalColor(hex: Int, alpha: CGFloat = 1.0) -> UIColor {
        let r = CGFloat((hex & 0xFF0000) >> 16) / 255.0
        let g = CGFloat((hex & 0x00FF00) >> 8)  / 255.0
        let b = CGFloat((hex & 0x0000FF) >> 0)  / 255.0
        return UIColor(red: r, green: g, blue: b, alpha: alpha)
    }
}
